package com.lzq.course.server.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.course.server.domain.User;
import com.lzq.course.server.domain.UserExample;
import com.lzq.course.server.dto.LoginUserDto;
import com.lzq.course.server.dto.ResourceDto;
import com.lzq.course.server.dto.UserDto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.exception.BusinessException;
import com.lzq.course.server.exception.BusinessExceptionCode;
import com.lzq.course.server.mapper.UserMapper;
import com.lzq.course.server.mapper.my.MyUserMapper;
import com.lzq.course.server.util.CopyUtil;
import com.lzq.course.server.util.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class UserService {

    private final static Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private MyUserMapper myUserMapper;

    /**
     * example 这个文件很有用
     * 可以帮我们生成where order 查询
     * 不用单独写sql的增删改查
     */
    public void list(PageDto<UserDto> pageDto) {
        // 分页查询 页码不是从0开始
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        // 排序
        UserExample userExample = new UserExample();

        // 查询
        List<User> userList = userMapper.selectByExample(userExample);

        PageInfo<User> pageInfo = new PageInfo<>(userList);
        pageDto.setTotal(pageInfo.getTotal());

        List<UserDto> userDtoList = CopyUtil.copyList(userList, UserDto.class);

        pageDto.setList(userDtoList);
    }

    /**
     * 保存 修改
     * @param userDto
     */
    public void save(UserDto userDto) {
        User copyUser = CopyUtil.copy(userDto, User.class);

        if (StringUtils.isEmpty(userDto.getId())) {
            // 新增
            // 八位的 id
            copyUser.setId(UuidUtil.getShortUuid());

            Date now = new Date();

            // 查询用户是否存在
            User UserDb = selectByLoginName(copyUser.getLoginName());
            if(UserDb != null) {
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            } else {
                // 不存在
                insertUser(copyUser);
            }
        } else {
            // 编辑
            copyUser.setPassword(null); // 编辑清空密码 编辑密码单独接口
            userMapper.updateByPrimaryKeySelective(copyUser);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询用户名是否存在
     * @param loginName
     * @return
     */
    public User selectByLoginName(String loginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /**
     * 插入用户
     * @param user
     */
    public void insertUser(User user) {
        userMapper.insert(user);
    }

    /**
     * 重置密码
     * @param userDto
     */
    public void savePassword(UserDto userDto) {
        User user = new User();
        user.setId(userDto.getId());
        user.setPassword(userDto.getPassword());
        userMapper.updateByPrimaryKeySelective(user); // 按主键选择性更新
    }

    /**
     * 用户登录
     * 1.判断用户名
     * 2.判断密码
     * @param userDto
     * @return
     */
    public LoginUserDto login(UserDto userDto) {
        User userDb = selectByLoginName(userDto.getLoginName());
        if (StringUtils.isEmpty(userDb)) {
            LOG.info("用户名不存在，userDto:{}", userDto);
            throw new BusinessException(BusinessExceptionCode.USER_LOGIN_ERROR);
        } else {
            if (userDto.getPassword().equals(userDb.getPassword())) {
                LoginUserDto loginUser = CopyUtil.copy(userDb, LoginUserDto.class);
                // 回去用户权限
                setAuth(loginUser);
                return loginUser;
            } else {
                LOG.info("密码错误，用户密码:{}，数据库密码：{}", userDto.getPassword(), userDb.getPassword());
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_ERROR);
            }
        }
    }

    /**
     * 为登录用户读取权限有哪些
     */
    public void setAuth(LoginUserDto loginUserDto) {
        List<ResourceDto> resourceDtoList = myUserMapper.findResources(loginUserDto.getId());
        loginUserDto.setResources(resourceDtoList); // 设置权限

        // 整理后端的接口权限 只要request
        HashSet<String> requestSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(resourceDtoList)) {
            for (int i = 0; i < resourceDtoList.size(); i++) {
                String req = resourceDtoList.get(i).getRequest();// "["/system/admin/user/list","/system/admin/user/save"]"
                List<String> requestList = JSON.parseArray(req, String.class); // 解析成数组
                if (!CollectionUtils.isEmpty(requestList)) {
                    requestSet.addAll(requestList);
                }
            }
        }
        LOG.info("有权限的请求：{}", requestSet);
        loginUserDto.setRequests(requestSet); // 后端接口权限校验用
    }
}
